﻿#include <cmath>
#include <QDebug>
#include <QFontMetrics>
#include "element.h"


DrawLCircle::DrawLCircle(void)
    : m_start(0, 0),
      m_end(0, 0),
      m_centre(0, 0),
      m_radius (0)
{
    m_drawType = LCIRCLE;
    m_state = Element::DS_IDLE;
}

void DrawLCircle::build(QPoint p1, QPoint p2)
{
    setStartPoint(p1);
    setEndPoint(p2);
}

DrawLCircle::~DrawLCircle(void)
{
}


int	DrawLCircle::mouseMove(QPoint point)
{
    if( m_state == Element::DS_STATE1 )
    {
        setTempEndPoint(point);
        return 1;
    }
    return 0;
}

int	DrawLCircle::mouseLButtonPress(QPoint point)
{
    if( m_state == Element::DS_IDLE )
    {
        setStartPoint(point);
        return 1;
    }
    return 0;
}

inline void DrawLCircle::setStartPoint(QPoint start)
{
    m_start = start;
    m_end = start;
    m_centre = start;
    m_state = Element::DS_STATE1;
}

void DrawLCircle::setTempEndPoint(QPoint end)
{
    m_end = end;
    m_centre = (m_start + m_end) / 2;
    QPoint pt = (m_start - m_end) / 2;
    m_radius = hypot(pt.x(), pt.y());
}
void DrawLCircle::setEndPoint(QPoint end)
{
    m_end = end;
    m_centre = (m_start + m_end) / 2;
    QPoint pt = (m_start - m_end) / 2;
    m_radius = hypot(pt.x(), pt.y());
    m_textBox.moveTo(m_centre);
    updateText();
    m_state = Element::DS_FINISH;
}

int DrawLCircle::mouseLButtonRelease(QPoint point)
{
    if( m_state == Element::DS_STATE1 )
    {
        setEndPoint(point);
        if( m_radius < 6 )
        {
            m_state = Element::DS_ERROR;
        }
        return 1;
    }
    return 0;
}
void DrawLCircle::draw( QPainter &painter )
{
    if( m_state != Element::DS_IDLE )
    {
        painter.save();
        painter.setPen(m_linePen);
        int x, y, width, height;
        x = m_centre.x() - m_radius;
        y = m_centre.y() - m_radius;
        width = 2 * m_radius;
        height = 2 * m_radius;
        painter.drawArc ( x, y, width, height, 0, 16 * 360 );
        if( m_state == Element::DS_STATE1 )
        {
            //painter.save();
            QPen pen = m_linePen;
            pen.setStyle(Qt::DotLine);
            painter.setPen(pen);
            painter.drawLine(m_start, m_end);
            //painter.restore();
        }
        else if( m_state == Element::DS_FINISH )
        {
            painter.setFont(m_textFont);
            painter.drawText(m_textBox, m_text);
        }
        painter.restore();
    }

}
void DrawLCircle::updateText(void)
{
    if(m_radius * m_scale >= 500.0)
    {
        m_text = QString::fromUtf8("D = %1 mm").arg(2 * m_radius * m_scale / 1000.0, 2, 'f', 2);
    }
    else
    {
        m_text = QString::fromUtf8("D = %1 μm").arg(2 * m_radius * m_scale, 2, 'f', 2);
    }
    QFontMetrics fm(m_textFont);
    int textWidth = fm.width(m_text);
    int textHeight = fm.height();
    m_textBox.setWidth(textWidth);
    m_textBox.setHeight(textHeight);
}

void DrawLCircle::computeBox()
{

}
